/**
 * @see 该页面是查询成绩的页面
 */
import { getXnxqListGxdx, getXnxqList } from '../../../utils/util'
import { API_CONFIG } from '../../../config'
let xnxqList = []

Page({
  data: {
    index: xnxqList.length - 1,
    xnxqList,
    userInfo: '', // 用户信息
    bgStyle: `background-image: url("${API_CONFIG.staticUrl}wx-x-mai/bg.jpg")`, // 背景图片
    sTotalCredits: '', // 在校总学分
    sYearAverage: '', // 历年平均分
    sTermCredits: '', // 学期总学分
    sTermAverage: '', // 学期平均分
    aGradeListData: [], // 查询成绩数据
    showAdvert: true,
    appMsg: {
      type: '', // 状态
      show: false, // 是否展示
    },
  },
  onLoad() {
    let schoolConfig = wx.getStorageSync('schoolConfig')
    xnxqList =
      schoolConfig.schoolCode + '' === '4145010593'
        ? getXnxqListGxdx()
        : getXnxqList()
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      xnxqList,
      index: xnxqList.length - 1,
    })
    this.gradeInfo()
  },
  openMall() {
    wx.navigateTo({
      url: '/pages/web/web?path=https://xwx.gzzmedu.com/file-agency/', // 文件代办
      // url: '/pages/web/web?path=https://xwx.gzzmedu.com/xwx-mall', // 商城模块
    })
  },
  /**
   * @see 关闭头部广告
   */
  closeAdvert() {
    this.setData({
      showAdvert: false,
    })
  },
  /**
   * @see 获取查询成绩列表
   */
  gradeInfo() {
    const { xnxqList, index } = this.data
    const request = {
      schoolYear: xnxqList[index].id,
    }
    this.setData({
      appMsg: {
        type: 'loading',
        show: true,
      },
    })
    wx.$API['schoolStudy/getStuGrade'](request)
      .then((response) => {
        this.setData({
          appMsg: {
            type: 'loading',
            show: false,
          },
        })
        const data = response.data
        const dataLength = response.data.length
        if (dataLength === 0) {
          this.setData({
            appMsg: {
              type: 'none',
              show: true,
            },
          })
        } else {
          this.setData({
            sTotalCredits: data[0].totalCredits,
            sYearAverage: data[0].yearAverage,
            sTermCredits: data[0].termCredits,
            sTermAverage: data[0].termAverage,
            aGradeListData: data,
          })
        }
      })
      .catch((error) => {
        // 防止直接进入查成绩页面，token无效请求失败
        if (error === 'Invalid token') {
          this.gradeInfo()
        } else {
          this.setData({
            appMsg: {
              type: 'err',
              show: true,
            },
          })
        }
      })
  },
  /**
   * @see 点击刷新页面
   */
  clickMsgButton() {
    this.gradeInfo()
  },
  /**
   * @see 点击选择下拉学年学期
   */
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value,
    })
    this.gradeInfo()
  },
  onShareAppMessage() {
    return {
      path: '/pages/home/index',
    }
  },
})
